package com.knowif.backend.controller;

import com.knowif.backend.service.UserWeChatProxy;
import com.knowif.util.commonUtil.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

@RestController
@RequestMapping("/wechatProxy/")
public class WechatListenController {
    @Autowired
    private UserWeChatProxy userWeChatProxy;
    private final static String WECHAT_TOKEN = "WechatMessage";

    @GetMapping("wechat")
    public String checkSignature(String signature,String timestamp,String nonce,String echostr){
        System.out.println("get");
        String[] arr = new String[] { timestamp, nonce, WECHAT_TOKEN };
        Arrays.sort(arr);
        String s = arr[0] + arr[1] + arr[2];
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            byte[] digest = md.digest(s.getBytes("utf-8"));
            if(StringUtil.byte2Hex(digest).equals(signature)){
                return echostr;
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return null;
    }

    @PostMapping("wechat")
    public void wechatMessage(HttpServletRequest request, HttpServletResponse response){
        userWeChatProxy.weChatproxy(request, response);
    }


}
